<?php
/**
 * Description
 * User: duanwenjie
 * Date: 2019/5/9
 * Time: 11:59 AM
 */

namespace app\index\service;
use app\common\ConfigBase;
use app\common\model\ToolModel;
use think\Db;
use think\Exception;

class WarehouseService
{
    static public function getWarehouseList($param, $is_download = false)
    {
        try{
            $where = "where 1 = 1 ";
            $pageNumber = isset($param['page']) ? $param['page'] : 1;
            $pageData = isset($param['limit']) ? $param['limit'] : 20;
            $warehouse_name = isset($param['warehouse_name']) ? $param['warehouse_name'] : '';  //仓库名称
            $warehouse_id = isset($param['id']) ? $param['id'] : '';  //仓库代码
            $country_name = isset($param['country_name']) ? $param['country_name'] : '';  //所属国家
            $status = isset($param['status']) ? $param['status'] : '';  //状态
            $type = isset($param['type']) ? $param['type'] : '';  //仓库类型
            $offset = ($pageNumber - 1) * $pageData;
            $limit = " LIMIT $offset,$pageData";

            if (!empty($warehouse_name)) {
                $warehouse_name = trim($warehouse_name);
                $where .= " AND BW.warehouse_name = '{$warehouse_name}'";
            }
            if (!empty($warehouse_id)) {
                $warehouse_id = trim($warehouse_id);
                $where .= " AND BW.id = {$warehouse_id}";
            }
            if (!empty($country_name)) {
                $country_name = trim($country_name);
                $where .= " AND BW.base_country_name = '{$country_name}'";
            }
            if (!empty($status)) {
                $where .= " AND BW.status = {$status}";
            }
            if (!empty($type)) {
                $where .= " AND BW.type = {$type}";
            }

            $sqlCount = "SELECT COUNT(BW.id) num FROM base_warehouse BW {$where}";
            $countArr = ToolModel::queryData($sqlCount);
            if (empty($countArr) || $countArr[0]['num'] == 0) {
                return array('total' => 0, 'list' => array());
            }
            $fileds = 'BW.id,BW.warehouse_name,BC.company_name,BW.address,BS.shop_name,
                      case BW.type when 1 then "店仓" when 2 then "国家仓" when 3 then "加盟" end type_name,
                      case BW.status when 1 then "启用" when -1 then "禁用" end status_name,BW.type,BW.status,
                      BW.operator,BW.update_time';

            $sql = "SELECT {$fileds} FROM base_warehouse BW LEFT JOIN base_company BC ON BW.base_company_id = BC.id
            LEFT JOIN base_shop BS ON BW.base_shop_id = BS.id {$where} ORDER BY BW.id DESC {$limit}";
            if ($is_download) $sql = "SELECT {$fileds} FROM base_warehouse BW LEFT JOIN base_company BC ON BW.base_company_id = BC.id 
            LEFT JOIN base_shop BS ON BW.base_shop_id = BS.id {$where} ORDER BY BW.id DESC ";

            $list = ToolModel::queryData($sql);
            $data = array();
            $data['total'] = intval($countArr[0]['num']);
            $data['list'] = $list;

            return $data;
        }catch (Exception $e){
            trace($e->getMessage(), 'error');
            throw new Exception($e->getMessage());
        }
    }


    /**
     * 校验新增/编辑数据
     * @param $params
     * @param string $id
     * @return array
     * @throws Exception
     * @author duanwenjie
     */
    static public function checkData($params, $id = "")
    {
        try{
            $type = $params['type'];
            $shop_name = $params['shop_name'];
            $warehouse_name = $params['warehouse_name'];
            $res = Db::name('base_shop')->where('shop_name', '=', $shop_name)->find();
            $res2 = Db::name('base_company')->where('company_name', '=', $shop_name)->find();
            if ($type == 1){
                /*校验店铺*/
                if (empty($res)) returnJson(200, "操作失败！店铺：({$shop_name})不存在");
                $base_shop_id = $res['id']; // 店铺ID
                $base_company_id = $res['base_company_id']; // 公司ID
                $base_country_id = $res['base_country_id']; // 国家ID
                $base_country_name = $res['base_country_name']; // 国家名称
            }else{
                /*校验公司*/
                if (empty($res2)) returnJson(200, "操作失败！公司：({$shop_name})不存在");
                $base_shop_id = 0; // 店铺ID为空
                $base_company_id = $res2['id']; // 公司ID
                $base_country_id = $res2['base_country_id']; // 国家ID
                $base_country_name = $res2['base_country_name']; // 国家名称
            }

            /* ==检验数据，店仓类型，确保店铺==>仓库唯一，国家仓类型，一个公司有且只有一个国家仓== */
            if (empty($id)){
                /*新增需校验仓库*/
                $res3 = Db::name('base_warehouse')->where('warehouse_name', '=', $warehouse_name)->find();
                if (!empty($res3)) returnJson(200, "操作失败！仓库：({$warehouse_name})已存在");
                if ($type == 1){
                    $check_shop = Db::name('base_warehouse')->where('base_shop_id', '=', $base_shop_id)->find();
                    if (!empty($check_shop))returnJson(200, "操作失败！店铺：({$shop_name})在仓库列表中已存在");
                }else{
                    $check_company = Db::name('base_warehouse')->where('base_company_id', '=', $base_company_id)
                        ->where('type', '=', 2)->find();
                    if (!empty($check_company))returnJson(200, "操作失败！公司：({$base_country_name})在仓库列表中已存在国家仓");
                }
            }else{
                $res_ = Db::name('base_warehouse')->where('id', '=', $id)->find();
                if (isset($res_['warehouse_name']) && $res_['warehouse_name'] != $params['warehouse_name']){
                    /*编辑的仓库名称发生改变，需校验仓库*/
                    $res4 = Db::name('base_warehouse')->where('warehouse_name', '=', $warehouse_name)->find();
                    if (!empty($res4)) returnJson(200, "操作失败！仓库：({$warehouse_name})已存在");
                }
                if ($type == 1){
                    $shop_name_ = isset((ConfigBase::getShopAll())[$res_['base_shop_id']]) ? (ConfigBase::getShopAll())[$res_['base_shop_id']] : "";
                    if (!empty($shop_name_) && $shop_name_ != $params['shop_name']){
                        /*编辑的店铺名发生改变，需校验店铺*/
                        $check_shop = Db::name('base_warehouse')->where('base_shop_id', '=', $base_shop_id)->find();
                        if (!empty($check_shop))returnJson(200, "操作失败！店铺：({$shop_name})在仓库列表中已存在");
                    }
                }else{
                    $company_name_ = isset((ConfigBase::getCompanyAll())[$res_['base_company_id']]) ? (ConfigBase::getCompanyAll())[$res_['base_company_id']] : "";
                    if (!empty($company_name_) && $company_name_ != $params['shop_name']){
                        /*编辑的公司名发生改变，需校验公司*/
                        $check_company = Db::name('base_warehouse')->where('base_company_id', '=', $base_company_id)->find();
                        if (!empty($check_company))returnJson(200, "操作失败！公司：({$shop_name})在仓库列表中已存在");
                    }
                }
            }

            $data = array("base_company_id" => $base_company_id, "base_country_id" => $base_country_id, "base_country_name" => $base_country_name, "base_shop_id" => $base_shop_id);

            return $data;
        }catch (Exception $e){
            trace($e->getMessage(), 'error');
            throw new Exception($e->getMessage());
        }
    }


}